import { useState, useEffect } from "react";
import { useLocation } from "react-router-dom";
function useScrollbar() {
  const [scrollDirection, setScrollDirection] = useState("up");
  const [fixed, setFixed] = useState("");
  const location = useLocation(); // 路由变更检测
  const [previousPosition, setPreviousPosition] = useState(0);
  const handleScroll = () => {
    const currentPosition =
      document.documentElement.scrollTop || document.body.scrollTop;
    const clientHeight = window.innerHeight; //内部高度
    const scrollHeight = document.documentElement.scrollHeight; //滚动条高度
    console.log("ZHI", currentPosition, clientHeight, scrollHeight);

    if (currentPosition > 100) {
      if (currentPosition + clientHeight === scrollHeight) {
        setScrollDirection(() => "bottom");
      } else {
        if (currentPosition > previousPosition) {
          setScrollDirection(() => "down");
        } else if (currentPosition < previousPosition) {
          setScrollDirection(() => "up");
        }
      }
      setPreviousPosition(() => currentPosition);
    }
    if (currentPosition > 1600) {
      setFixed(() => "fixed");
    } else {
      setFixed(() => "");
    }
  };
  useEffect(() => {
    window.addEventListener("scroll", handleScroll);
  });

  useEffect(() => {
    setScrollDirection("up");
    setPreviousPosition(0);
    setFixed("");
  }, [location.pathname]);

  return {
    scrollDirection,
    fixed,
  };
}

export default useScrollbar;
